import * as Cesium from 'cesium';

export class MeasurementTools {
  constructor(cesiumManager) {
    this.cesiumManager = cesiumManager;
    this.drawHandler = null;
    this.activeEntity = null;
    this.tempEntities = [];
  }

  // 测量距离
  measureDistance() {
    if (!this.cesiumManager || !this.cesiumManager.viewer) return;
    
    const viewer = this.cesiumManager.viewer;
    
    // 如果正在绘制其他内容，先取消
    if (this.drawHandler) {
      this.drawHandler.destroy();
    }
    
    const positions = [];
    this.activeEntity = viewer.entities.add({
      polyline: {
        positions: new Cesium.CallbackProperty(() => {
          if (positions.length >= 2) {
            return positions;
          }
          return null;
        }, false),
        width: 3,
        material: Cesium.Color.YELLOW
      }
    });
    
    this.tempEntities.push(this.activeEntity);
    
    this.drawHandler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    
    this.drawHandler.setInputAction((click) => {
      const cartesian = viewer.camera.pickEllipsoid(click.position, viewer.scene.globe.ellipsoid);
      if (cartesian) {
        positions.push(cartesian);
        
        if (positions.length >= 2) {
          const distance = Cesium.Cartesian3.distance(positions[positions.length-2], positions[positions.length-1]);
          const midpoint = Cesium.Cartesian3.midpoint(positions[positions.length-2], positions[positions.length-1], new Cesium.Cartesian3());
          
          const label = viewer.entities.add({
            position: midpoint,
            label: {
              text: distance.toFixed(2) + ' m',
              font: '14px sans-serif',
              fillColor: Cesium.Color.WHITE,
              outlineColor: Cesium.Color.BLACK,
              outlineWidth: 2,
              style: Cesium.LabelStyle.FILL_AND_OUTLINE,
              pixelOffset: new Cesium.Cartesian2(0, -20)
            }
          });
          this.tempEntities.push(label);
        }
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    
    this.drawHandler.setInputAction((click) => {
      if (positions.length < 2) {
        viewer.entities.remove(this.activeEntity);
        this.tempEntities.pop();
      } else {
        this.activeEntity.polyline.positions = positions.slice();
      }
      this.drawHandler.destroy();
      this.drawHandler = null;
      this.activeEntity = null;
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
  }

  // 测量面积
  measureArea() {
    if (!this.cesiumManager || !this.cesiumManager.viewer) return;
    
    const viewer = this.cesiumManager.viewer;
    
    // 如果正在绘制其他内容，先取消
    if (this.drawHandler) {
      this.drawHandler.destroy();
    }
    
    const positions = [];
    this.activeEntity = viewer.entities.add({
      polygon: {
        hierarchy: new Cesium.CallbackProperty(() => {
          if (positions.length >= 3) {
            return new Cesium.PolygonHierarchy(positions);
          }
          return null;
        }, false),
        material: Cesium.Color.YELLOW.withAlpha(0.5)
      }
    });
    
    this.tempEntities.push(this.activeEntity);
    
    this.drawHandler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    
    this.drawHandler.setInputAction((click) => {
      const cartesian = viewer.camera.pickEllipsoid(click.position, viewer.scene.globe.ellipsoid);
      if (cartesian) {
        positions.push(cartesian);
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    
    this.drawHandler.setInputAction((click) => {
      if (positions.length < 3) {
        viewer.entities.remove(this.activeEntity);
        this.tempEntities.pop();
      } else {
        this.activeEntity.polygon.hierarchy = new Cesium.PolygonHierarchy(positions.slice());
        
        // 计算面积
        const ellipsoid = viewer.scene.globe.ellipsoid;
        let area = 0;
        if (positions.length >= 3) {
          const coordinates = positions.map(p => {
            const cartographic = ellipsoid.cartesianToCartographic(p);
            return [Cesium.Math.toDegrees(cartographic.longitude), Cesium.Math.toDegrees(cartographic.latitude)];
          });
          
          // 简单的面积计算（近似）
          area = this.calculatePolygonArea(coordinates);
        }
        
        // 添加面积标签
        if (positions.length > 0) {
          const center = positions.reduce((acc, pos) => {
            return Cesium.Cartesian3.add(acc, pos, acc);
          }, new Cesium.Cartesian3());
          Cesium.Cartesian3.divideByScalar(center, positions.length, center);
          
          const label = viewer.entities.add({
            position: center,
            label: {
              text: area.toFixed(2) + ' km²',
              font: '14px sans-serif',
              fillColor: Cesium.Color.WHITE,
              outlineColor: Cesium.Color.BLACK,
              outlineWidth: 2,
              style: Cesium.LabelStyle.FILL_AND_OUTLINE
            }
          });
          this.tempEntities.push(label);
        }
      }
      this.drawHandler.destroy();
      this.drawHandler = null;
      this.activeEntity = null;
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
  }

  // 测量高度
  measureHeight() {
    if (!this.cesiumManager || !this.cesiumManager.viewer) return;
    
    const viewer = this.cesiumManager.viewer;
    
    // 如果正在绘制其他内容，先取消
    if (this.drawHandler) {
      this.drawHandler.destroy();
    }
    
    this.drawHandler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    
    this.drawHandler.setInputAction((click) => {
      const cartesian = viewer.camera.pickEllipsoid(click.position, viewer.scene.globe.ellipsoid);
      if (cartesian) {
        const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
        const longitude = Cesium.Math.toDegrees(cartographic.longitude);
        const latitude = Cesium.Math.toDegrees(cartographic.latitude);
        
        // 获取椭球体高度
        const ellipsoidHeight = cartographic.height;
        
        // 创建临时标签显示椭球体高度
        const entity = viewer.entities.add({
          position: cartesian,
          point: {
            pixelSize: 10,
            color: Cesium.Color.RED,
            outlineColor: Cesium.Color.WHITE,
            outlineWidth: 2
          },
          label: {
            text: `高度: ${ellipsoidHeight.toFixed(2)} 米`,
            font: '14px sans-serif',
            fillColor: Cesium.Color.WHITE,
            outlineColor: Cesium.Color.BLACK,
            outlineWidth: 2,
            style: Cesium.LabelStyle.FILL_AND_OUTLINE,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            pixelOffset: new Cesium.Cartesian2(0, -20)
          }
        });
        this.tempEntities.push(entity);
        
        // 检查是否有有效的地形提供器
        if (viewer.terrainProvider && 
            viewer.terrainProvider.ready &&
            !(viewer.terrainProvider instanceof Cesium.EllipsoidTerrainProvider)) {
          
          // 首先尝试使用getHeight方法获取地形高度
          const terrainHeight = viewer.scene.globe.getHeight(cartographic);
          
          if (typeof terrainHeight === 'number' && !isNaN(terrainHeight)) {
            // 更新标签显示地形高度
            entity.label.text = `地形高度: ${terrainHeight.toFixed(2)} 米\n椭球体高度: ${ellipsoidHeight.toFixed(2)} 米`;
          } else {
            // 如果getHeight无法获取高度，则使用sampleTerrain
            Cesium.sampleTerrainMostDetailed(viewer.terrainProvider, [cartographic])
              .then((updatedPositions) => {
                if (updatedPositions && updatedPositions.length > 0) {
                  const terrainHeight = updatedPositions[0].height;
                  if (typeof terrainHeight === 'number' && !isNaN(terrainHeight)) {
                    entity.label.text = `地形高度: ${terrainHeight.toFixed(2)} 米\n椭球体高度: ${ellipsoidHeight.toFixed(2)} 米`;
                  } else {
                    entity.label.text = `地形高度: 获取失败\n椭球体高度: ${ellipsoidHeight.toFixed(2)} 米`;
                  }
                } else {
                  entity.label.text = `地形高度: 获取失败\n椭球体高度: ${ellipsoidHeight.toFixed(2)} 米`;
                }
              })
              .catch((error) => {
                console.error('地形高度获取失败:', error);
                // 如果地形高度获取失败，至少显示椭球体高度
                entity.label.text = `地形高度: 获取失败\n椭球体高度: ${ellipsoidHeight.toFixed(2)} 米`;
              });
          }
        } else {
          // 没有有效的地形提供器时，仅显示椭球体高度
          entity.label.text = `椭球体高度: ${ellipsoidHeight.toFixed(2)} 米\n(无地形数据)`;
        }
      }
      this.drawHandler.destroy();
      this.drawHandler = null;
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  }

  // 圆形框选
  circleSelection() {
    if (!this.cesiumManager || !this.cesiumManager.viewer) return;
    
    const viewer = this.cesiumManager.viewer;
    
    if (this.drawHandler) {
      this.drawHandler.destroy();
    }
    
    let center = null;
    let radius = 0;
    
    this.drawHandler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    
    this.drawHandler.setInputAction((click) => {
      const cartesian = viewer.camera.pickEllipsoid(click.position, viewer.scene.globe.ellipsoid);
      if (cartesian) {
        if (!center) {
          center = cartesian;
        } else {
          radius = Cesium.Cartesian3.distance(center, cartesian);
          const entity = viewer.entities.add({
            position: center,
            ellipse: {
              semiMajorAxis: radius,
              semiMinorAxis: radius,
              material: Cesium.Color.CYAN.withAlpha(0.3),
              outline: true,
              outlineColor: Cesium.Color.CYAN
            }
          });
          this.tempEntities.push(entity);
          
          // 执行框选逻辑
          this.performCircleSelection(center, radius);
          
          this.drawHandler.destroy();
          this.drawHandler = null;
        }
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  }

  // 矩形框选
  rectangleSelection() {
    if (!this.cesiumManager || !this.cesiumManager.viewer) return;
    
    const viewer = this.cesiumManager.viewer;
    
    if (this.drawHandler) {
      this.drawHandler.destroy();
    }
    
    let startCorner = null;
    
    this.drawHandler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    
    this.drawHandler.setInputAction((click) => {
      const cartesian = viewer.camera.pickEllipsoid(click.position, viewer.scene.globe.ellipsoid);
      if (cartesian) {
        if (!startCorner) {
          startCorner = cartesian;
        } else {
          const entity = viewer.entities.add({
            rectangle: {
              coordinates: new Cesium.CallbackProperty(() => {
                return Cesium.Rectangle.fromCartesianArray([startCorner, cartesian]);
              }, false),
              material: Cesium.Color.MAGENTA.withAlpha(0.3),
              outline: true,
              outlineColor: Cesium.Color.MAGENTA
            }
          });
          this.tempEntities.push(entity);
          
          // 执行框选逻辑
          this.performRectangleSelection(startCorner, cartesian);
          
          this.drawHandler.destroy();
          this.drawHandler = null;
        }
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  }

  // 多边形框选
  polygonSelection() {
    if (!this.cesiumManager || !this.cesiumManager.viewer) return;
    
    const viewer = this.cesiumManager.viewer;
    
    if (this.drawHandler) {
      this.drawHandler.destroy();
    }
    
    const positions = [];
    this.activeEntity = viewer.entities.add({
      polygon: {
        hierarchy: new Cesium.CallbackProperty(() => {
          if (positions.length >= 3) {
            return new Cesium.PolygonHierarchy(positions);
          }
          return null;
        }, false),
        material: Cesium.Color.GREEN.withAlpha(0.3),
        outline: true,
        outlineColor: Cesium.Color.GREEN
      }
    });
    
    this.tempEntities.push(this.activeEntity);
    
    this.drawHandler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    
    this.drawHandler.setInputAction((click) => {
      const cartesian = viewer.camera.pickEllipsoid(click.position, viewer.scene.globe.ellipsoid);
      if (cartesian) {
        positions.push(cartesian);
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    
    this.drawHandler.setInputAction((click) => {
      if (positions.length < 3) {
        viewer.entities.remove(this.activeEntity);
        this.tempEntities.pop();
      } else {
        this.activeEntity.polygon.hierarchy = new Cesium.PolygonHierarchy(positions.slice());
        // 执行框选逻辑
        this.performPolygonSelection(positions);
      }
      this.drawHandler.destroy();
      this.drawHandler = null;
      this.activeEntity = null;
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
  }

  // 执行圆形框选
  performCircleSelection(center, radius) {
    console.log('执行圆形框选，中心点:', center, '半径:', radius);
    // 实际应用中，这里应该遍历场景中的实体并判断是否在圆内
  }

  // 执行矩形框选
  performRectangleSelection(corner1, corner2) {
    console.log('执行矩形框选，对角点:', corner1, corner2);
    // 实际应用中，这里应该遍历场景中的实体并判断是否在矩形内
  }

  // 执行多边形框选
  performPolygonSelection(positions) {
    console.log('执行多边形框选，顶点:', positions);
    // 实际应用中，这里应该遍历场景中的实体并判断是否在多边形内
  }

  // 简单多边形面积计算函数
  calculatePolygonArea(coordinates) {
    // 这里使用简单的平面近似计算
    let area = 0;
    const n = coordinates.length;
    
    for (let i = 0; i < n; i++) {
      const j = (i + 1) % n;
      area += coordinates[i][0] * coordinates[j][1];
      area -= coordinates[j][0] * coordinates[i][1];
    }
    
    area = Math.abs(area) / 2.0;
    return area * 100; // 粗略转换为平方公里
  }

  getTempEntities() {
    return this.tempEntities;
  }

  setTempEntities(entities) {
    this.tempEntities = entities;
  }

  clear() {
    if (!this.cesiumManager || !this.cesiumManager.viewer) return;
    
    const viewer = this.cesiumManager.viewer;
    
    this.tempEntities.forEach(entity => {
      viewer.entities.remove(entity);
    });
    
    this.tempEntities = [];
    
    if (this.drawHandler) {
      this.drawHandler.destroy();
      this.drawHandler = null;
    }
    
    this.activeEntity = null;
  }
}